Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
ICSM Computer
24-Apr-2025In Java,
nullis often used to represent the absence of a value. However, this can lead to problems likeNullPointerExceptionif not handled properly.Java 8 introduced the
Optional<T>class injava.utilto provide a better way to model optional (nullable) values.1. What is
Optional<T>?Optional<T>is a container object that may or may not contain an unknown value.If any value is present then
isPresent()returnstrueandget()returns value.2. Creating Optional Instances
3. Common Optional Methods
isPresent()ifPresent(Consumer)orElse(T)orElseGet(Supplier)orElseThrow()NoSuchElementExceptionif value is absentmap(Function)flatMap(Function)4. Examples
a. Safe Access
b. Execute If Present
c. Avoid NullPointerException
Instead of:
With
Optional:d. Using
orElseGet()andorElseThrow()5. When to Use Optional
Good for:
nullchecksAvoid:Optionalis used in real-world APIs or want to convert anull-prone method to useOptional.